/* Filename: rcver.c
 * Description: 报式socket组播接收
 * ./rcver 239.255.255.249 enp1s0
 * Last modified: humble 2021-09-07 11:14
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "proto.h"

#define IPSTRSIZE (40)

static void usage(char *argv0);

int main(int argc, char **argv)
{
    int sd;
    struct sockaddr_in laddr,raddr;
    //struct msg_st rbuf;
    char rbuf[256] = {0};
    socklen_t raddr_len;
    char ipstr[IPSTRSIZE];

    if(argc != 3){ fprintf(stderr, "argc !=3\n"); usage(argv[0]); exit(1); }

    sd = socket(AF_INET, SOCK_DGRAM, 0/*IPPROTO_UDP*/);
    if(sd < 0){ perror("socket()"); exit(1); }

    struct ip_mreqn mreq;
    //加入第一个组播组
    inet_pton(AF_INET, argv[1], &mreq.imr_multiaddr);
    inet_pton(AF_INET, "0.0.0.0" , &mreq.imr_address);
    mreq.imr_ifindex = if_nametoindex(argv[2]); //网卡索引号
    if(setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0){
        perror("setsockopt(IP_ADD_MEMBERSHIP,if_name)");
        exit(1);
    }

#if 0 //加入第二个组播组
    inet_pton(AF_INET, MGROUP, &mreq.imr_multiaddr);
    inet_pton(AF_INET, "0.0.0.0" , &mreq.imr_address);
    mreq.imr_ifindex = if_nametoindex("eth0"); //网卡索引号
    if(setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0){
        perror("setsockopt(IP_ADD_MEMBERSHIP,if_name)");
        exit(1);
    }
#endif

    laddr.sin_family = AF_INET;
    laddr.sin_port = htons(atoi(RCVPORT));
    inet_pton(AF_INET, "0.0.0.0", &laddr.sin_addr);

    if(bind(sd, (void *)&laddr, sizeof(laddr)) < 0){ perror("bind()"); exit(1); }

    /* 重要：若没初始化该值，则会导致第一次收到数据出错 */
    raddr_len = sizeof(raddr);

    while(1){
        //recvfrom(sd, &rbuf, sizeof(rbuf), 0, (void *)&raddr, &raddr_len);
        recvfrom(sd, rbuf, sizeof(rbuf), 0, (void *)&raddr, &raddr_len);
        inet_ntop(AF_INET, &raddr.sin_addr, ipstr, IPSTRSIZE);
        printf("---MESSAGE FROM:%s:%d---\n", ipstr, ntohs(raddr.sin_port));
        //printf("name:%s\n", rbuf.name);
        //printf("math:%d\n", ntohl(rbuf.math));
        //printf("chinese:%d\n", ntohl(rbuf.chinese));
        printf("[%s]\n\n", rbuf);
    }

    setsockopt(sd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq)); //退出所有组播组
    close(sd);
    return 0;
}

static void usage(char *argv0)
{
#define USAGE "Usage:\n\
  %s <ipaddr> <if_name>\n"
    printf(USAGE, argv0);
}
